package com.atguigu.controller;

import com.atguigu.entity.*;
import com.atguigu.result.Result;
import com.atguigu.service.*;
import com.atguigu.vo.HouseQueryVo;
import com.atguigu.vo.HouseVo;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/house")
public class HouseController {

    @DubboReference
    private HouseService houseService;
    @DubboReference
    private CommunityService communityService;
    @DubboReference
    private HouseImageService houseImageService;
    @DubboReference
    private HouseBrokerService houseBrokerService;
    @DubboReference
    private UserFollowService userFollowService;


    /**
     * 房源列表
     */
    @PostMapping("/list/{pageNum}/{pageSize}")
    @ResponseBody
    public Result<PageInfo<HouseVo>> findListPage(@RequestBody HouseQueryVo houseQueryVo,
                               @PathVariable("pageNum") Integer pageNum,
                               @PathVariable("pageSize") Integer pageSize) {

//        调用服务层方法，带条件查询分页信息
        PageInfo<HouseVo> pageInfo = houseService.findListPage(pageNum, pageSize, houseQueryVo);
        return Result.ok(pageInfo);
    }

//    前台获取房源详情处理器
    @RequestMapping("/info/{id}")
    @ResponseBody
    public Result info(@PathVariable("id") Long id, HttpServletRequest request) {
//        房子信息 house
        House house = houseService.getById(id);
//        小区信息 community
        Community community = communityService.getById(house.getCommunityId());
//        经纪人信息 broker
        List<HouseBroker> houseBrokerList = houseBrokerService.findListByHouseId(id);
//        房源图片 houseimage
        List<HouseImage> houseImage1List = houseImageService.findList(id, 1);
//        当前用户是否关注房源 follow
        boolean isFollow = false;
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("USER");
        if (null != userInfo) {
            isFollow = userFollowService.isFollowed(userInfo.getId(),id);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("house", house);
        map.put("community", community);
        map.put("houseBrokerList", houseBrokerList);
        map.put("houseImage1List", houseImage1List);
        map.put("isFollow", isFollow);
        return Result.ok(map);
    }

}